package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jt.exception.ServiceException;
import com.jt.mapper.ItemDescMapper;
import com.jt.pojo.EasyUITable;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jt.mapper.ItemMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author Song
 * @since 2020/11/3
 */
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ItemDescMapper itemDescMapper;


    @Override
    public EasyUITable findItemByPage(Integer page, Integer rows) {

		/*IPage<Item> page = new Page<>(curr, rows);
		page =itemMapper.selectPage(page, null);*/

        int startIndex = (page - 1) * rows;
        //2.数据库记录
        List<Item> itemList = itemMapper.findItemByPage(startIndex, rows);
        //3.查询数据库总记录数
        Long total = Long.valueOf(itemMapper.selectCount(null));
        //4.将数据库记录 封装为VO对象
        return new EasyUITable(total, itemList);

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addItem(Item item, ItemDesc itemDesc) {
        if (itemMapper.insert(item)<=0){
            throw new ServiceException("");
        }
        itemDesc.setItemId(item.getId());
        if (itemDescMapper.insert(itemDesc)<=0){
            throw new ServiceException("");
        }

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteItem(Long[] id) {
        if (itemMapper.deleteBatchIds(Arrays.asList(id)) <= 0
                || itemDescMapper.deleteBatchIds(Arrays.asList(id)) <= 0) {
            throw new ServiceException("删除item失败");
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateItem(Item item, ItemDesc itemDesc) {
        itemDesc.setItemId(item.getId());
        if (itemMapper.updateById(item) <= 0 || itemDescMapper.updateById(itemDesc) <= 0) {
            throw new ServiceException("更新item失败");
        }
    }

    @Override
    public void reshelf(Long[] ids, Integer status) {
        Item item = new Item();
        item.setStatus(status);
        UpdateWrapper<Item> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", Arrays.asList(ids));
        if (itemMapper.update(item, updateWrapper) < 0) {
            throw new ServiceException();
        }
    }

    @Override
    public ItemDesc findItemDescById(Long itemId) {
        return itemDescMapper.selectById(itemId);
    }
}
